<template>
  <PageWrapper dense contentClass="p-16px">
    <CollapseContainer v-show="state.current == 0" title="客户信息">
      <BasicForm @register="registerForm">
        <template #customerTransactionId="{ model, field }">
          <Select v-model:value="model[field]" placeholder="请选择">
            <SelectOption v-for="item in state.userList" :key="item.userId" :value="item.userId">
              {{ item.userName }}
            </SelectOption>
          </Select>
        </template>
        <!-- 客户评级 -->
        <template #customerRating="{ model, field }">
          <Rate v-model:value="model[field]" />
        </template>
        <!-- 标签 -->
        <template #customerLabel>
          <template v-for="tag in state.customerLabel" :key="tag">
            <Tooltip v-if="tag.length > 20" :title="tag">
              <Tag :closable="true" color="blue" @close="handleClose(tag)">
                {{ `${tag.slice(0, 20)}...` }}
              </Tag>
            </Tooltip>
            <Tag v-else :closable="true" color="blue" @close="handleClose(tag)">
              {{ tag }}
            </Tag>
          </template>
          <Input v-if="state.inputVisible" ref="inputRef" type="text" size="small" :style="{ width: '78px' }"
            v-model:value="state.inputValue" @blur="handleInputConfirm" @keyup.enter="handleInputConfirm" />
          <Tag v-else @click="showInput" style="background: #fff; border-style: dashed">
            <plus-outlined />
            新增标签
          </Tag>
        </template>
        <!-- Logo -->
        <template #customerAvatar="{ model, field }">
          <ImageUpload v-model:value="model[field]" :api="uploadApi"
            :accept="['.jpg', '.jpeg', '.gif', '.png', '.webp']" />
        </template>
      </BasicForm>
    </CollapseContainer>
    <CollapseContainer v-show="state.current == 1 || isUpdate" title="地址" class="mt-8px">
      <Address :recordId="state.customerId" />
    </CollapseContainer>
    <CollapseContainer v-show="state.current == 1 || isUpdate" title="联系人" class="mt-8px">
      <Contact :recordId="state.customerId" type="customer" />
    </CollapseContainer>
    <div class="flex justify-end gap-8px mt-8px">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="state.current < state.steps.length - 1" type="primary" @click="handleSubmit(false)">保存</a-button>
      <a-button v-if="state.current < state.steps.length - 1 && !isUpdate" type="primary"
        @click="handleSubmit(true)">新增地址/联系人</a-button>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
import { BasicForm, useForm } from '@/components/Form';
import { onMounted, ref, reactive, nextTick } from 'vue';
import { addCustomer, updateCustomer, getCustomer } from '@/api/customer';
import { userList } from '@/api/system/user';
import { uploadApi } from '@/api/upload';
import { drawerSchemas } from './customer.data';
import { Tag, Rate, Tooltip, Input, Select } from 'ant-design-vue';
import { CollapseContainer } from '@/components/Container';
import { PageWrapper } from '@/components/Page';
import { Address } from '@/components/Address';
import { Contact } from '@/components/Contact';
import { ImageUpload } from '@/components/Upload';
import { useTabs } from '@/hooks/web/useTabs';
import { useGo } from '@/hooks/web/usePage';
import { PageEnum } from '@/enums/pageEnum';
defineOptions({ name: 'CustomerEdit' });
import { useRoute } from 'vue-router';
const SelectOption = Select.Option;
const { closeCurrent, setTitle } = useTabs();
/** 拿到路由的id */
const route = useRoute();
const isUpdate = (route.query.type as string) === 'update';
const customerId = route.query.id as string;
document.title = isUpdate ? '编辑客户' : '新增客户';
setTitle(document.title);
const go = useGo();
const emit = defineEmits(['register', 'reload']);

const [registerForm, { setFieldsValue, resetForm, validate }] = useForm({
  // layout: 'vertical',
  labelWidth: 100,
  name: 'user-drawer',
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: drawerSchemas,
});

async function handleSubmit(flag: boolean) {
  try {
    const data = {
      ...(await validate()),
      customerCorporateName: '666',
      customerLabel: state.customerLabel.join(','),
    };

    if (isUpdate) {
      await updateCustomer(data);
    } else {
      const res = (await addCustomer(data)) as any;
      state.customerId = res;
    }
    if (flag) {
      state.current++;
    } else {
      handleCancel();
    }
  } catch (e) {
    console.log('e', e);
  } finally {
  }
}

async function handleCancel() {
  resetForm();
  closeCurrent();
  go({ path: '/customer/customer' as PageEnum });
}
const inputRef = ref();
const state = reactive({
  customerId: '',
  userList: [],
  customerLabel: [],
  inputVisible: false,
  inputValue: '',
  current: 0,
  steps: [
    {
      title: '客户信息',
    },
    {
      title: '地址/联系人',
    },
  ],
});
const handleClose = (removedTag: string) => {
  const customerLabel = state.customerLabel.filter((tag) => tag !== removedTag);
  state.customerLabel = customerLabel;
};

const showInput = () => {
  state.inputVisible = true;
  nextTick(() => {
    inputRef.value.focus();
  });
};

const handleInputConfirm = () => {
  const inputValue = state.inputValue as never;
  let customerLabel = state.customerLabel;
  if (inputValue && customerLabel.indexOf(inputValue) === -1) {
    customerLabel = [...customerLabel, inputValue];
  }
  Object.assign(state, {
    customerLabel,
    inputVisible: false,
    inputValue: '',
  });
};
const getUserInfo = async () => {
  const res = (await getCustomer(customerId)) as any;
  res.customerTransactionId = res.customerTransactionId ? Number(res.customerTransactionId) : '';
  state.customerId = res.customerId;
  state.customerLabel = res.vendorLabel ? res.customerLabel.split(',') : [];
  setFieldsValue(res);
};
const getUserData = async () => {
  const { rows } = await userList({ pageNum: 1, pageSize: 10000 });
  state.userList = rows;
};
onMounted(() => {
  getUserData();
  customerId && getUserInfo();
});
</script>

<style lang="less" scoped>
:deep(.ant-tag) {
  margin-right: 6px;
  margin-bottom: 6px;
}
</style>
